package com.ohy.tencent.config;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

@Aspect
@Component
@Slf4j
public class WebLogAspect {

    @Pointcut("execution(public * com.ohy.tencent.controller.*.*(..))")
    public void webLog() {
    }

    /**
     * 使用AOP前置通知拦截请求参数信息
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> enu = request.getParameterNames();
        String param="";
        while (enu.hasMoreElements()) {
            String name = enu.nextElement();
            param+=name + "=" + request.getParameter(name)+"&";
        }
        IpInfo ipInfo = new IpInfo(request.getRemoteAddr(), getArea(request.getRemoteAddr()), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), request.getRequestURL().toString(),param);
        log.info(ipInfo.toString());
    }

    /**
     * 后置通知
     *
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        //logger.info("RESPONSE : " + ret);
    }

    public static String getArea(String ip) {
        try {
            String url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=" + ip + "&resource_id=6006";
            HttpRequest get = HttpUtil.createGet(url);
            HttpResponse execute = get.execute();
            JSONArray data = JSONObject.parseObject(execute.body()).getJSONArray("data");
            return data.size() > 0 ? data.getJSONObject(0).getString("location") : "";
        } catch (Exception e) {
            log.error("获取ip位置异常", e);
            return null;
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class IpInfo {
        private String ip;
        private String area;
        private String date;
        private String url;
        private String param;
    }
}